import smtplib
import time
from email.mime.text import MIMEText
from email.header import Header
import requests

'''
该脚本用于抢购FunHPC的GPU服务器
'''

TOKEN = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1dWlkIjoiNzY4MjQ2NDk5MzI4ODgzODYwNDQzMTA0MjM1NTIyMzEiLCJleHAiOjE3MzI4MzgyMTcsIm5iZiI6MTczMjU1MDIwN30._9gnMY5-o1L6eFXwj9nZXvHS2TY3bsOch5Y-OGeK6KA"
NEED_CARD = 8
headers = {
    "Authorization": TOKEN,
    "Content-Type": "application/json",
    "Host": "funhpc.com",
    "Origin": "https://www.funhpc.com",
    "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0'
}

def send_mail():
    subject = 'go buy A800 server'
    body = 'A800 have 8 cards, to buy it'
    msg = MIMEText(body, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = '2010362389@qq.com'
    msg['To'] = '545466093@qq.com'
    smtp_server = 'smtp.qq.com'
    smtp_port = 587
    sender_email = '2010362389@qq.com'
    password = 'hbiopvjkfoercigj'
    try:
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.starttls()
            server.login(sender_email, password)
            server.sendmail(sender_email, [msg['To']], msg.as_string())
        print('success send email')
    except smtplib.SMTPException as e:
        print(e)

def check_is_ok():
    url = "https://funhpc.com/api/cvm/name"
    body =  {
        "page_number": 1,
        "page_size": 999,
        "name": "A800-PCIE-80GB"
    }

    response = requests.post(url, headers=headers, json=body)

    if response.status_code == 200:
        json_data = response.json()
        data = json_data['data']['list']
        for item in data:
            if item['cluster'] == 4 and item['available_cards'] >= NEED_CARD:
                return item['id']
        print("success get server data:")
    else:
        print(f"request fail, code: {response.status_code}")
        print(response.text)
    return -1

def buy_server(id):
    print(f"prepare buy server: {id}")
    url = "https://funhpc.com/api/instance/create"
    body = {
        "uuid": "76824649932888386044310423552231",
        "cvm_id": id,
        "rental_type": 1,
        "cards": 8,
        "image_name": "snowharbor.deepln.com:31443/user_image2024/ubuntu20.04-py3.8:v62",
        "days": 0,
        "is_cpu": False,
        "local": 0,
        "remote": 0,
        "local_price": 0,
        "remote_price": 0,
        "pvc_name": "veteyercikxwsotb-glow"
    }

    response = requests.post(url, headers=headers, json=body)
    if response.status_code == 200:
        print("success buy a server")
        return True
    else:
        return False

while True:
    time.sleep(2)
    id = check_is_ok()
    if id != -1:
        send_mail()
        if buy_server(id):
            time.sleep(600)
